<template>
  <a-modal title="新增角色" v-model="show" :maskClosable="false" :width="1050" placement="right" :closable="true"
    @cancel="onClose" :footer="null" :visiable="roleAddVisiable">
    <a-form :form="form">
      <a-form-item label="角色级别" v-bind="formItemLayout" :validateStatus="validateStatusCode" :help="helpCode">
        <a-select mode="default" :allowClear="true" style="width: 100%" @blur="handleRoleCodeBlur"
          v-decorator="['roleCode', { rules: [{ required: true, message: '请选择角色级别' }] }]">
          <a-select-option v-for="r in roleCodeData" :key="r.label">{{ r.value }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='角色名称' v-bind="formItemLayout" :validateStatus="validateStatusRoleName" :help="helpRoleName">
        <a-input @blur="handleRoleNameBlur"
          v-decorator="['roleName', { rules: [{ required: true, message: '请输入角色名称' }] }]" />
      </a-form-item>
      <a-form-item label='角色描述' v-bind="formItemLayout">
        <a-textarea :rows="4" v-decorator="[
        'roleDesc',
        {
          rules: [
            { max: 50, message: '长度不能超过50个字符' }
          ]
        }]">
        </a-textarea>
      </a-form-item>
      <a-form-item label='权限选择' style="margin-bottom: 4rem!important;" :validateStatus="menuSelectStatus"
        :help="menuSelectHelp" v-bind="formItemLayout">
        <a-tree :key="menuTreeKey" ref="menuTree" :checkable="true" :checkStrictly="checkStrictly" @check="handleCheck"
          @expand="handleExpand" :expandedKeys="expandedKeys" :treeData="menuTreeData">
        </a-tree>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="2" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          菜单树
          <a-icon type="up" />
        </a-button>
      </a-dropdown>
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-modal>
</template>
<script>
const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'RoleAdd',
  props: {
    roleAddVisiable: {
      default: false
    },
    roleInstId: '',
    roleCodeData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      menuTreeKey: +new Date(),
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      validateStatus: '',
      menuSelectStatus: '',
      validateStatusCode: '',
      help: '',
      menuSelectHelp: '',
      helpCode: '',
      role: {
        roleName: '',
        remark: '',
        menuId: ''
      },
      checkedKeys: [],
      expandedKeys: [],
      menuTreeData: [],
      allTreeKeys: [],
      checkStrictly: false,
      validateStatusRoleName: '',
      helpRoleName: ''
    }
  },
  computed: {
    show: {
      get: function () {
        return this.roleAddVisiable
      },
      set: function () {
      }
    }
  },
  methods: {
    reset() {
      this.menuTreeKey = +new Date()
      this.expandedKeys = this.checkedKeys = []
      this.validateStatus = this.help = ''
      this.validateStatusCode = this.helpCode = ''
      this.loading = false
      this.form.resetFields()
    },
    onClose() {
      this.reset()
      this.$emit('close')
    },
    expandAll() {
      this.expandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeys = []
    },
    handleCheck(checkedKeys) {
      this.checkedKeys = checkedKeys
      let checkedArr = Object.is(checkedKeys.checked, undefined) ? checkedKeys : checkedKeys.checked
      if (checkedArr.length) {
        this.menuSelectStatus = ''
        this.menuSelectHelp = ''
      } else {
        this.menuSelectStatus = 'error'
        this.menuSelectHelp = '请选择相应的权限'
      }
    },
    handleExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    async handleRoleNameBlur () {
        this.validateStatusRoleName = 'success'
        this.helpRoleName = ''
        let roleName = this.form.getFieldValue('roleName')
        roleName = typeof roleName === 'undefined' ? '' : roleName.trim()
        if (roleName.length) {
            if (roleName.length > 10) {
                this.validateStatusRoleName = 'error'
                this.helpRoleName = '角色名称不能超过10个字符'
            } else {
                // if(this.orgRoleName != roleName ) {
                    this.validateStatusRoleName = 'validating'
                    const res = await this.$get(`admin/upmprole/check` ,{
                        instId:this.roleInstId,
                        roleName:roleName
                    });
                    if (res.data.status) {
                        this.validateStatusRoleName = 'success'
                        this.helpRoleName = ''
                    } else {
                        this.validateStatusRoleName = 'error'
                        this.helpRoleName = '抱歉，该角色名称已存在'
                    }
                // }
            }
        } else {
            this.validateStatusRoleName = 'error'
            this.helpRoleName = '角色名称不能为空'
        }
    },
    handleSubmit() {
      let checkedArr = Object.is(this.checkedKeys.checked, undefined) ? this.checkedKeys : this.checkedKeys.checked
      if (this.validateStatusCode !== 'success') {
        this.handleRoleCodeBlur()
      }
      if (this.validateStatusRoleName !== 'success') {
        this.handleRoleNameBlur()
      } else if (checkedArr.length === 0) {
        this.menuSelectStatus = 'error'
        this.menuSelectHelp = '请选择相应的权限'
      } else {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.setRoleFields()
            this.loading = true
            this.role.menuId = checkedArr.join(',')
            this.role.instId = this.roleInstId;
            this.$post('admin/upmprole', {
              ...this.role
            }).then((res) => {
              if (res.status === 200) {
                this.reset()
                this.$emit('success')
                this.loading = false
              } else {
                this.$message.error(res.data.message);
                return false;
              }
            }).catch(() => {
              this.loading = false
            })
          }
        })
      }
    },
    handleRoleCodeBlur() {
      let roleCode = this.form.getFieldValue('roleCode')
      roleCode = typeof roleCode === 'undefined' ? '' : roleCode.trim()
      if (roleCode.length) {
        this.validateStatusCode = 'success'
        this.helpCode = ''
      } else {
        this.validateStatusCode = 'error'
        this.helpCode = '角色级别不能为空'
      }
    },
    setRoleFields() {
      let values = this.form.getFieldsValue(['instId', 'status', 'roleCode', 'roleName', 'roleDesc'])
      if (typeof values !== 'undefined') {
        Object.keys(values).forEach(_key => { this.role[_key] = values[_key] })
      }
    }
  },
  watch: {
    roleAddVisiable() {
      if (this.roleAddVisiable) {
        var params = {};
        params.channelType = "00";
        this.$get('admin/upmpmenu', {
          ...params
        }).then((r) => {
          this.menuTreeData = r.data.rows.children
          this.allTreeKeys = r.data.ids
        })
        /*this.$get('admin/upmprole/getRoleCode/'+this.roleInstId+'/add').then((r) => {
            this.roleCodeData = r.data
        })*/
        // this.form.getFieldDecorator('deptName')
        // this.form.setFieldsValue("instId",this.roleInstId);
      }
    }
  }
}
</script>
